<?php
/**
 * 平台红包分享模型
 * 
 * @copyright  Copyright (c) 中国追溯
 * @since      File available since Release v1.1
 */
defined('InShopNC') or exit('Access Invalid!');
class redpacket_shareModel extends Model {
        
    public function __construct(){
        parent::__construct('redpacket_share');
    }

    /**
     * 计算用户分享引流数量
     * @param  int $member_id    会员id
     * @param  int $rpacket_t_id 模板id
     * @return int
     */
    public function countDrainageQuantity($member_id, $rpacket_t_id)
    {
        $map = array(
            'rpacket_t_id' => (int)$rpacket_t_id,
            'parent_member_id' => (int)$member_id,
        );
        return $this->table('redpacket_share')->where($map)->count();
    }

    /**
     * 增加红包模板分享次数
     * @param array $map 过滤条件
     */
    public function addShareNumber($member_id = 0, $rpacket_t_id = 0)
    {
        $result = false;
        // 是否存在该数据
        $map = array(
            'member_id' => (int)$member_id,
            'rpacket_t_id' => (int)$rpacket_t_id
        );
        $if_exist = $this->ifExist($map);
        if ($if_exist) {    //存在数据增加分享次数
            $result = $this->table('redpacket_share')->where($map)->setInc('share_number', 1);
        } else {    //不存在，添加分享记录
            //添加分享记录
            $add_data = array(
                'rpacket_t_id'     => $rpacket_t_id,
                'member_id'        => $member_id,
                'parent_member_id' => 0,
                'share_number'     => 1
            );
            $result = $this->addData($add_data);
        }
        return $result;
    }

    /**
     * 是否存在该数据
     * @param  array  $map 过滤条件
     * @return bool
     */
    public function ifExist($map = array())
    {
        return $this->getOneData($map, 'share_id') ? true : false;
    }

    /**
     * 获取单条数据
     * @param  array  $map   过滤条件
     * @param  string $field 返回列
     * @param  string $order 排序方式
     * @return array
     */
    public function getOneData($map = array(), $field = '*', $order = 'share_id asc')
    {
        return $this->table('redpacket_share')->where($map)->field($field)->order($order)->find();
    }

    /**
     * 新增数据
     * @param bool / int
     */
    public function addData($add_data)
    {
        return $this->table('redpacket_share')->insert($add_data);
    }

}